const config = require("../config.js");
const {mysql2Service} = require("./mysql2Service.js");
let normalResult = require("../normalResult.js")
const {mysqlService} = require("./mysqlService");

const baseModelUseMysql2 = {
    getAll: async (sql) => {
        let result = JSON.parse(normalResult)
        try {
            result.data = await mysql2Service(sql, []);
            return result
        } catch (error) {
            result = Object.assign(result, config.result.error)
            return result
        }
    },

    getDataById: async (sql, id) => {
        let result = JSON.parse(normalResult)
        sql += ` where id = ${id}`
        try {
            let r = await mysql2Service(sql, []);
            if (r.length) {
                result.data = r[0];
                return result;
            } else {
                result = Object.assign(result, config.result.notData)
                return result;
            }
        } catch (error) {
            result = Object.assign(result, config.result.sqlError)
            return result
        }
    },

    add: async (table, params) => {
        let result = JSON.parse(normalResult)
        if (params.id) delete params.id;
        let sql = `insert into ${table} (`;
        sql += Object.keys(params).join(",");
        sql += `) values (`;
        sql += Object.values(params).map(item => {
            return `'${item}'`
        }).join(",");
        sql += ')'
        try {
            let res = await mysql2Service(sql, []);
            result.data = res.insertId;
            return result;
        } catch (error) {
            //TODO handle error
            result = Object.assign(result, config.result.error)
            return result
        }
    },

};

module.exports = {
    baseModelUseMysql2: baseModelUseMysql2
}
